package com.example.demo.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @author Buer
 */
public class HttpSends {

    /** 接收封装好的url进行Get请求 */
    public String sendGet(String url) {
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置超时时间5s
            connection.setConnectTimeout(5 * 1000);
            // 设置读取时间15s
            connection.setReadTimeout(15 * 1000);
            // 设置请求需要返回的数据类型和字符集类型
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 定义 BufferedReader输入流来读取URL的响应，设置utf8防止中文乱码
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            // 关闭BufferedReader输入流
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /*接收url和字符串形式json进行Post请求*/
    public String sendPost(String url, String param) {
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置超时时间5s
            connection.setConnectTimeout(5 * 1000);
            // 设置读取时间15s
            connection.setReadTimeout(15 * 1000);
            // 设置请求需要返回的数据类型和字符集类型
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            // 允许写出
            connection.setDoOutput(true);
            // 允许读入
            connection.setDoInput(true);
            // 不使用缓存
            connection.setUseCaches(false);
            // 获取URLConnection对象对应的输出流
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader in =
                new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}